package com.example.filedemo.control;


import cn.hutool.core.io.FileUtil;
import com.example.filedemo.constant.Constants;
import com.example.filedemo.mapper.FileMapper;
import com.example.filedemo.pojo.UserFile;
import com.example.filedemo.service.FileService;
import com.example.filedemo.utils.Doc2PdfUtils;
import com.example.filedemo.utils.Pdf2htmlEXUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class FileControl {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileMapper fileMapper;

    @GetMapping("/u/{url}")
    public String url(@PathVariable("url") String url, ModelMap modelMap) {
        List list = fileMapper.findUserAll();
        modelMap.addAttribute("file", list);
        return url;
    }


    @PostMapping("/upload")
    public String upload(MultipartFile multipartFile, ModelMap modelMap) throws IOException {
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取后缀名
        String extension = "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
        // 新文件名
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + extension;
        // 文件大小
        long size = multipartFile.getSize();
        // 文件类型
        String contentType = multipartFile.getContentType();

        // 生成文件夹
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dataDirPath = dateFormat;
        File dataDir = new File(dataDirPath);
        if (!dataDir.exists()) {
            dataDir.mkdirs();
        }
        // 处理文件上传
        File file_wait = new File(dataDir, newFileName);

        if (originalFilename != null && !"".equals(originalFilename)) {
            // 使用绝对路径，相对路径会报错
            multipartFile.transferTo(file_wait.getAbsoluteFile());

            // 文件信息放入数据库
            UserFile userFile = new UserFile();
            userFile.setOldFileName(originalFilename)
                    .setNewFileName(newFileName)
                    .setExt(extension)
                    .setSize(String.valueOf(size))
                    .setPath(dataDirPath)
                    .setType(contentType)
                    .setUploadTime(new Date());
            fileService.save(userFile);
        }

        List list = fileMapper.findUserAll();
        modelMap.addAttribute("file", list);

        return "index";
    }


    @GetMapping("/download")
    public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
        openStyle = openStyle == null ? "attachment" : openStyle;
        //获取文件信息
        UserFile file = fileService.findById(id);
        //根据   文件名字 和 文件存储路径 获取文件输入流
        String realpath = ResourceUtils.getURL(file.getPath()).getPath();
        // 获取文件输入流
        FileInputStream fileInputStream = new FileInputStream(new File(realpath, file.getNewFileName()));
        //附件下载
        response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(file.getOldFileName(), "UTF-8"));
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(fileInputStream, outputStream);
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);

    }


    @RequestMapping("/word2pdf")
    public String word2pdf(HttpServletResponse response, ModelMap modelMap) {
        Doc2PdfUtils.doc2pdf(Constants.docx, Constants.convertPdfPath);
        System.out.println("转换成功");
        Pdf2htmlEXUtil.pdf2html(Constants.convertPdfPath, Constants.convertHtmlPath);

        String readString = FileUtil.readString(Constants.convertHtmlPath, StandardCharsets.UTF_8);
        modelMap.addAttribute("co", readString);
//            Doc2PdfUtils.onlineReader(file,response);
        System.out.println("执行完毕");
        return "index";
    }
}
